package type.fragment.Adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;

import java.util.List;

import type.fragment.TypeFragment;

public class CategoryListAdapter extends BaseAdapter {
    private Context context;
    private List<type.fragment.CategoryModel> categoryList;
    private OnCategorySelectedListener listener;

    public void setSelectedPosition(int position) {
    }

    // 定义回调接口
    public interface OnCategorySelectedListener {
        void onCategorySelected(int position);
    }

    public CategoryListAdapter(Context context, List<type.fragment.CategoryModel> categoryList, OnCategorySelectedListener listener) {
        this.context = context;
        this.categoryList = categoryList;
        this.listener = listener;
    }

    @Override
    public int getCount() {
        return categoryList != null? categoryList.size() : 0;
    }

    @Override
    public Object getItem(int position) {
        return categoryList != null? categoryList.get(position) : null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @RequiresApi(api = android.os.Build.VERSION_CODES.M)
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(
                    android.R.layout.simple_list_item_1, parent, false);
            holder = new ViewHolder();
            holder.textView = convertView.findViewById(android.R.id.text1);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        if (categoryList != null &&!categoryList.isEmpty()) {
            holder.textView.setText(categoryList.get(position).getCategoryName());
        }

        holder.textView.setBackgroundColor(
                ((ListView) parent).isItemChecked(position)?
                        ContextCompat.getColor(context, android.R.color.darker_gray) :
                        ContextCompat.getColor(context, android.R.color.white)
        );

        convertView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onCategorySelected(position);
                ((ListView) parent).setItemChecked(position, true);
            }
        });

        return convertView;
    }

    static class ViewHolder {
        TextView textView;
    }
}